Popular Searches
Popular Course Categories
Popular Courses

Assertions

TestNG / PyTest

Assertions in TestNG

Assertions are one of the most important parts of TestNG-based Selenium automation. An assertion is a validation statement used to compare the actual result produced by an application with the expected result defined by the test case. If the actual result matches the expected condition, the assertion passes. If the expected condition is not satisfied, the assertion fails and TestNG records the test accordingly.

In Selenium automation, WebDriver performs actions such as opening a browser, navigating to a page, entering values, clicking buttons, selecting options, and interacting with web elements. Assertions verify whether those actions produced the expected application behavior.

Course Resource: Selenium Training | Register for Course Demo


1. What are Assertions?

An assertion is a validation mechanism provided by TestNG that checks whether an actual value or condition matches the expected result. Assertions are commonly used inside @Test methods to determine whether a test scenario has passed or failed.

Assert.assertEquals(actual, expected);

For example, if the expected page title is Login Page and the actual page title is also Login Page, the assertion passes.

String actualTitle = "Login Page";

String expectedTitle = "Login Page";

 

Assert.assertEquals(actualTitle, expectedTitle);


2. Why are Assertions Important in Selenium?

Selenium performs browser automation, but simply performing browser actions does not prove that the application behaved correctly. Assertions provide the validation layer that determines whether the expected behavior actually occurred.

  • Validate expected application behavior.
  • Compare actual and expected values.
  • Verify page titles.
  • Verify URLs.
  • Verify text messages.
  • Verify element visibility.
  • Verify element state.
  • Verify login results.
  • Verify search results.
  • Verify cart contents.
  • Verify form validation messages.
  • Verify navigation behavior.
  • Mark test cases as passed or failed.
  • Improve automation reliability and reporting.


3. Assertion Flow in Selenium Automation

Test Method

     |

     v

Perform Selenium Action

     |

     v

Capture Actual Result

     |

     v

Define Expected Result

     |

     v

Perform Assertion

     |

     +------------------+

     |                  |

     v                  v

Condition True     Condition False

     |                  |

     v                  v

   PASS               FAIL


4. TestNG Assert Class

TestNG provides the Assert class for performing hard assertions.

import org.testng.Assert;

The most commonly used TestNG assertions include:

AssertionPurpose
assertEquals()Checks whether two values are equal.
assertNotEquals()Checks whether two values are different.
assertTrue()Checks whether a condition is true.
assertFalse()Checks whether a condition is false.
assertNull()Checks whether a value is null.
assertNotNull()Checks whether a value is not null.
assertSame()Checks whether two references point to the same object.
assertNotSame()Checks whether two references point to different objects.


5. Basic assertEquals()

assertEquals() compares two values and passes when the expected and actual values are equal.

import org.testng.Assert;

import org.testng.annotations.Test;

 

public class AssertionTest {

 

    @Test

    public void verifyTitle() {

        String actualTitle = "Login Page";

        String expectedTitle = "Login Page";

 

        Assert.assertEquals(actualTitle, expectedTitle);

    }

}

Here, the actual title and expected title are the same, so the assertion passes.


6. assertEquals() with Numbers

@Test

public void verifyCalculation() {

    int actual = 100;

    int expected = 100;

 

    Assert.assertEquals(actual, expected);

}

This assertion verifies that both numeric values are equal.


7. assertEquals() with Strings

@Test

public void verifyMessage() {

    String actualMessage = "Login successful";

    String expectedMessage = "Login successful";

 

    Assert.assertEquals(actualMessage, expectedMessage);

}

This is commonly used for validating confirmation messages, error messages, headings, labels, and other text values.


8. assertNotEquals()

assertNotEquals() verifies that two values are not equal.

@Test

public void verifyDifferentValues() {

    String actualStatus = "Active";

    String unexpectedStatus = "Inactive";

 

    Assert.assertNotEquals(actualStatus, unexpectedStatus);

}

The assertion passes because the two values are different.


9. assertTrue()

assertTrue() verifies that a Boolean condition is true.

@Test

public void verifyLogin() {

    boolean loginSuccessful = true;

 

    Assert.assertTrue(loginSuccessful);

}

This assertion is particularly useful in Selenium when verifying conditions such as element visibility, URL content, page state, or other Boolean conditions.


10. Selenium Example with assertTrue()

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

import org.testng.annotations.Test;

 

public class GoogleTest {

 

    @Test

    public void verifyGoogleTitle() {

        WebDriver driver = new ChromeDriver();

 

        try {

            driver.get("https://www.google.com");

 

            String title = driver.getTitle();

 

            Assert.assertTrue(title.contains("Google"));

        } finally {

            driver.quit();

        }

    }

}

The assertion checks whether the page title contains the word Google.


11. assertFalse()

assertFalse() verifies that a Boolean condition is false.

@Test

public void verifyLoginButtonState() {

    boolean condition = false;

 

    Assert.assertFalse(condition);

}

In Selenium, this can be useful when verifying that an element is not selected, a condition is not active, or an expected negative condition is satisfied.


12. assertNull()

assertNull() verifies that a reference or value is null.

@Test

public void verifyNullValue() {

    String value = null;

 

    Assert.assertNull(value);

}

This type of assertion is generally more common in API, Java, and framework-level validations than in direct UI validation.


13. assertNotNull()

assertNotNull() verifies that a value or object is not null.

@Test

public void verifyObject() {

    String username = "admin";

 

    Assert.assertNotNull(username);

}

It can be useful when validating that an object, response, page object, or test data value has been initialized.


14. assertSame()

assertSame() verifies that two references point to the same object.

@Test

public void verifySameObject() {

    String value = "Selenium";

    String sameReference = value;

 

    Assert.assertSame(value, sameReference);

}

This assertion checks object identity rather than simply checking whether two values contain the same text.


15. assertNotSame()

assertNotSame() verifies that two references do not point to the same object.

@Test

public void verifyDifferentObjects() {

    String first = new String("Selenium");

    String second = new String("Selenium");

 

    Assert.assertNotSame(first, second);

}

The two objects contain the same text but are separate object references.


16. Hard Assertions

TestNG's standard Assert methods are hard assertions. When a hard assertion fails, the current test method stops executing from that point.

@Test

public void verifyPage() {

    Assert.assertEquals(

        driver.getTitle(),

        "Dashboard"

    );

 

    System.out.println("This line executes only if the assertion passes.");

}

If the assertion fails, the statement after it is not executed within that test method.


17. Hard Assertion Execution Flow

Test Method

     |

     v

Assertion 1

     |

     +-- PASS --> Continue

     |

     +-- FAIL --> Stop Current Test Method

                      |

                      v

                    FAIL


18. Multiple Hard Assertions

@Test

public void verifyDashboard() {

    Assert.assertEquals(

        driver.getTitle(),

        "Dashboard"

    );

 

    Assert.assertTrue(

        driver.getCurrentUrl().contains("dashboard")

    );

 

    Assert.assertTrue(

        driver.findElement(By.id("logout")).isDisplayed()

    );

}

If the first assertion fails, the remaining statements in the current test method are not executed.


19. Soft Assertions

Soft assertions allow multiple validations to execute even when one validation fails. TestNG provides the SoftAssert class for this purpose.

import org.testng.annotations.Test;

import org.testng.asserts.SoftAssert;

 

public class DashboardTest {

 

    @Test

    public void verifyDashboard() {

        SoftAssert softAssert = new SoftAssert();

 

        softAssert.assertEquals("Dashboard", "Dashboard");

        softAssert.assertTrue(true);

        softAssert.assertEquals("User", "Admin");

 

        softAssert.assertAll();

    }

}

The test can continue after an individual soft assertion failure. The collected failures are evaluated when assertAll() is called.


20. Importance of assertAll()

assertAll() is essential when using TestNG SoftAssert. It evaluates the collected assertion failures and causes the test to fail if one or more soft assertions failed.

SoftAssert softAssert = new SoftAssert();

 

softAssert.assertTrue(true);

softAssert.assertEquals("Login", "Login");

softAssert.assertEquals("Dashboard", "Home");

 

softAssert.assertAll();

Without assertAll(), the collected soft assertion failures may not cause the test method to be reported as failed.


21. Hard Assertion vs Soft Assertion

FeatureHard AssertionSoft Assertion
ClassAssertSoftAssert
Execution after failureStops current test method.Continues with subsequent statements.
Multiple validationsLater validations may not execute after failure.Multiple validations can be collected.
FinalizationNo assertAll() required.assertAll() is required.
Typical useCritical validation.Multiple independent validations on one page.


22. Selenium Login Assertion

Assertions are frequently used to verify whether a login operation produced the expected result.

import org.openqa.selenium.By;

import org.testng.Assert;

import org.testng.annotations.Test;

 

public class LoginTest extends BaseTest {

 

    @Test

    public void verifyValidLogin() {

        driver.findElement(By.id("username"))

              .sendKeys("admin");

 

        driver.findElement(By.id("password"))

              .sendKeys("admin123");

 

        driver.findElement(By.id("login"))

              .click();

 

        Assert.assertTrue(

            driver.getCurrentUrl().contains("dashboard")

        );

    }

}

Here Selenium performs the login actions and TestNG verifies whether the browser navigated to the expected dashboard.


23. Assertion for Page Title

@Test

public void verifyPageTitle() {

    driver.get("https://example.com");

 

    String actualTitle = driver.getTitle();

 

    Assert.assertEquals(

        actualTitle,

        "Example Domain"

    );

}

Page-title assertions are useful for verifying navigation and page identity.


24. Assertion for Current URL

@Test

public void verifyURL() {

    driver.get("https://example.com/login");

 

    String actualURL = driver.getCurrentUrl();

 

    Assert.assertTrue(

        actualURL.contains("/login")

    );

}

This validates that the browser is currently on the expected application route.


25. Assertion for WebElement Visibility

@Test

public void verifyLoginButton() {

    boolean displayed =

        driver.findElement(By.id("login")).isDisplayed();

 

    Assert.assertTrue(displayed);

}

This verifies that the login button is visible to the user.


26. Assertion for WebElement Enabled State

@Test

public void verifyButtonEnabled() {

    boolean enabled =

        driver.findElement(By.id("login")).isEnabled();

 

    Assert.assertTrue(enabled);

}

isEnabled() can be used to verify whether an element is enabled for interaction.


27. Assertion for Checkbox Selection

@Test

public void verifyCheckboxSelected() {

    boolean selected =

        driver.findElement(By.id("terms")).isSelected();

 

    Assert.assertTrue(selected);

}

This is useful for validating checkbox and radio-button states.


28. Assertion for Text

@Test

public void verifyWelcomeMessage() {

    String actualMessage =

        driver.findElement(By.id("welcome")).getText();

 

    Assert.assertEquals(

        actualMessage,

        "Welcome, Admin"

    );

}

Text assertions are commonly used for headings, success messages, error messages, notifications, labels, and validation messages.


29. Assertion for Error Message

@Test

public void verifyInvalidLoginMessage() {

    driver.findElement(By.id("username"))

          .sendKeys("wrong");

 

    driver.findElement(By.id("password"))

          .sendKeys("wrong123");

 

    driver.findElement(By.id("login"))

          .click();

 

    String message =

        driver.findElement(By.id("error"))

              .getText();

 

    Assert.assertEquals(

        message,

        "Invalid username or password"

    );

}


30. Assertion for Element Presence

When validating that an element exists, Selenium operations should be handled carefully because findElement() throws an exception when the element cannot be found.

@Test

public void verifySearchBox() {

    Assert.assertTrue(

        driver.findElement(By.id("search")).isDisplayed()

    );

}

For more flexible presence checks, a framework can use findElements() and verify that the returned collection is not empty.

@Test

public void verifySearchBoxExists() {

    boolean exists =

        !driver.findElements(By.id("search")).isEmpty();

 

    Assert.assertTrue(exists);

}


31. Assertion with Custom Message

TestNG assertion methods can include a message that helps explain the reason for a failure.

@Test

public void verifyTitle() {

    String actualTitle = driver.getTitle();

 

    Assert.assertEquals(

        actualTitle,

        "Dashboard",

        "Dashboard page title is incorrect"

    );

}

Custom assertion messages can make reports and debugging easier.


32. Assertion with Selenium Waits

Assertions should normally be performed after the application reaches the required state. Selenium waits can be used to synchronize the test before validation.

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement dashboard =

    wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            By.id("dashboard")

        )

    );

 

Assert.assertTrue(dashboard.isDisplayed());

The wait handles synchronization, while the assertion validates the resulting condition.


33. Wait vs Assertion

FeatureWaitAssertion
PurposeSynchronizes test execution with application state.Validates the expected result.
Main QuestionIs the application ready?Is the result correct?
ExampleWait until element is visible.Assert that element is displayed.
Failure MeaningRequired condition was not reached within the wait.Actual result did not satisfy the expected condition.


34. Assertions in Arrange-Act-Assert Pattern

@Test

public void verifyLogin() {

    // Arrange

    String username = "admin";

    String password = "admin123";

 

    // Act

    loginPage.enterUsername(username);

    loginPage.enterPassword(password);

    loginPage.clickLogin();

 

    // Assert

    Assert.assertTrue(

        homePage.isDashboardDisplayed()

    );

}

The assertion is normally placed in the Assert section of the test method.


35. Multiple Assertions in a Test

Multiple assertions can be used when a single test scenario requires several related validations.

@Test

public void verifyDashboard() {

    Assert.assertEquals(

        driver.getTitle(),

        "Dashboard"

    );

 

    Assert.assertTrue(

        driver.findElement(By.id("welcome")).isDisplayed()

    );

 

    Assert.assertTrue(

        driver.findElement(By.id("logout")).isDisplayed()

    );

}

However, excessive assertions covering unrelated business scenarios can make a test difficult to understand. Related validations should generally remain together.


36. SoftAssert Example for Dashboard

import org.testng.annotations.Test;

import org.testng.asserts.SoftAssert;

 

public class DashboardTest extends BaseTest {

 

    @Test

    public void verifyDashboardElements() {

        SoftAssert softAssert = new SoftAssert();

 

        softAssert.assertEquals(

            driver.getTitle(),

            "Dashboard"

        );

 

        softAssert.assertTrue(

            driver.findElement(By.id("logo")).isDisplayed()

        );

 

        softAssert.assertTrue(

            driver.findElement(By.id("profile")).isDisplayed()

        );

 

        softAssert.assertTrue(

            driver.findElement(By.id("logout")).isDisplayed()

        );

 

        softAssert.assertAll();

    }

}


37. Assertions and Test Results

Test Method

     |

     v

Perform Action

     |

     v

Capture Actual Result

     |

     v

Assertion

     |

     +----------------+

     |                |

     v                v

   PASS             FAIL

     |                |

     v                v

Continue         Test Failure

     |                |

     +--------+-------+

              |

              v

         Test Report


38. Assertion Failure Example

@Test

public void verifyTitle() {

    String actualTitle = "Home Page";

    String expectedTitle = "Login Page";

 

    Assert.assertEquals(actualTitle, expectedTitle);

 

    System.out.println("This line will not execute.");

}

Because the actual value and expected value are different, the assertion fails and execution of the current test method stops at that assertion.


39. Assertion and Exception

Assertions and exceptions are different concepts. An assertion intentionally validates a condition, while an exception indicates an unexpected or exceptional condition during execution.

ConceptMeaning
AssertionChecks whether an expected condition is satisfied.
ExceptionRepresents an abnormal condition during program execution.
Example AssertionAssert.assertEquals(actual, expected)
Example ExceptionNoSuchElementException


40. Assertion vs Verification

In modern TestNG automation, assertions are used to explicitly validate test results. The word "verification" is often used more generally to describe the act of checking whether an expected condition has been met.

TermMeaning
AssertionA TestNG validation mechanism that can determine test success or failure.
VerificationThe broader testing activity of checking an expected behavior or result.


41. Assertions with Page Object Model

In a Page Object Model framework, page classes can expose meaningful methods or state information while test classes perform the final business assertions.

public class LoginPage {

    private WebDriver driver;

 

    private By username = By.id("username");

    private By password = By.id("password");

    private By loginButton = By.id("login");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void enterUsername(String value) {

        driver.findElement(username).sendKeys(value);

    }

 

    public void enterPassword(String value) {

        driver.findElement(password).sendKeys(value);

    }

 

    public void clickLogin() {

        driver.findElement(loginButton).click();

    }

}

Test Method

@Test

public void verifyValidLogin() {

    LoginPage loginPage =

        new LoginPage(driver);

 

    loginPage.enterUsername("admin");

    loginPage.enterPassword("admin123");

    loginPage.clickLogin();

 

    Assert.assertTrue(

        driver.getCurrentUrl().contains("dashboard")

    );

}


42. Assertions with Reusable Page Methods

A page object can also provide methods that return Boolean values or actual values to the test method.

public boolean isDashboardDisplayed() {

    return driver.findElement(

        By.id("dashboard")

    ).isDisplayed();

}

The test method can then perform the assertion:

@Test

public void verifyDashboard() {

    Assert.assertTrue(

        homePage.isDashboardDisplayed()

    );

}


43. Assertion for Dropdown Selection

Select country =

    new Select(driver.findElement(By.id("country")));

 

country.selectByVisibleText("India");

 

String selected =

    country.getFirstSelectedOption().getText();

 

Assert.assertEquals(selected, "India");

This verifies that the expected dropdown option was selected.


44. Assertion for Checkbox State

WebElement checkbox =

    driver.findElement(By.id("terms"));

 

checkbox.click();

 

Assert.assertTrue(

    checkbox.isSelected(),

    "Terms checkbox should be selected"

);


45. Assertion for Button State

WebElement submitButton =

    driver.findElement(By.id("submit"));

 

Assert.assertTrue(

    submitButton.isEnabled(),

    "Submit button should be enabled"

);


46. Assertion for URL After Navigation

driver.findElement(By.id("login")).click();

 

Assert.assertTrue(

    driver.getCurrentUrl().contains("dashboard"),

    "User was not redirected to dashboard"

);


47. Assertion for Page Source Content

String pageSource = driver.getPageSource();

 

Assert.assertTrue(

    pageSource.contains("Welcome"),

    "Welcome text was not found in page source"

);

Page-source assertions can be useful in some situations, but direct element-based validation is generally clearer when a specific UI element can be located reliably.


48. Assertion for Attribute Value

String placeholder =

    driver.findElement(By.id("username"))

          .getAttribute("placeholder");

 

Assert.assertEquals(

    placeholder,

    "Enter username"

);

This is useful for validating HTML attributes such as placeholder, value, class, href, title, and other relevant attributes.


49. Assertion for Multiple Related UI Elements

@Test

public void verifyLoginPage() {

    Assert.assertTrue(

        driver.findElement(By.id("username")).isDisplayed()

    );

 

    Assert.assertTrue(

        driver.findElement(By.id("password")).isDisplayed()

    );

 

    Assert.assertTrue(

        driver.findElement(By.id("login")).isDisplayed()

    );

}

These assertions verify that the important controls on the login page are available.


50. SoftAssert for Multiple UI Validations

@Test

public void verifyLoginPageElements() {

    SoftAssert softAssert = new SoftAssert();

 

    softAssert.assertTrue(

        driver.findElement(By.id("username")).isDisplayed()

    );

 

    softAssert.assertTrue(

        driver.findElement(By.id("password")).isDisplayed()

    );

 

    softAssert.assertTrue(

        driver.findElement(By.id("login")).isDisplayed()

    );

 

    softAssert.assertAll();

}

Soft assertions can be useful when you want to collect several independent UI validation failures from the same page before reporting the final result.


51. Assertion Messages and Debugging

Adding meaningful assertion messages can make failed automation tests easier to understand.

Assert.assertEquals(

    actualTitle,

    expectedTitle,

    "Page title does not match the expected title"

);

A good assertion message should describe what was expected or what business condition failed.


52. Common Mistakes with Assertions

Mistake 1: Performing Actions Without Validation

@Test

public void loginTest() {

    driver.findElement(By.id("login")).click();

 

    // No validation

}

A test that only performs actions may not prove that the expected result occurred.

Correct Approach

@Test

public void loginTest() {

    driver.findElement(By.id("login")).click();

 

    Assert.assertTrue(

        driver.getCurrentUrl().contains("dashboard")

    );

}

Mistake 2: Using the Wrong Expected Value

Assert.assertEquals(

    actualTitle,

    "Incorrect Title"

);

The expected value should come from the intended test requirement.

Mistake 3: Forgetting assertAll()

SoftAssert softAssert = new SoftAssert();

 

softAssert.assertTrue(false);

 

// Missing assertAll()

Always call assertAll() after completing the relevant soft validations.

Mistake 4: Using Hard Assertions for Unrelated Checks

If several independent page elements need to be validated and you want all validation failures reported together, SoftAssert may be more appropriate.

Mistake 5: Confusing Waits with Assertions

A wait synchronizes the test with application state. An assertion validates whether the resulting state is correct. They solve different problems.

Mistake 6: Using Assertions Before the Page Is Ready

If an application is dynamic, synchronize with the appropriate condition before validating the result.

Mistake 7: Using Weak Assertions

Assert.assertTrue(true);

This does not validate the application. Assertions should be based on meaningful actual application data or state.


53. Best Practices for Assertions

  • Always validate the important expected outcome of a test.
  • Use the most specific assertion available.
  • Keep expected values clear and meaningful.
  • Use descriptive assertion messages where helpful.
  • Use hard assertions for critical checkpoints.
  • Use SoftAssert when several independent validations need to be collected.
  • Always call assertAll() when using SoftAssert.
  • Synchronize dynamic pages before validating them.
  • Do not replace proper waits with arbitrary Thread.sleep() calls.
  • Keep assertions close to the behavior they validate.
  • Avoid unnecessary assertions that do not add test value.
  • Keep test data and expected results maintainable.
  • Use Page Object Model to keep Selenium implementation organized.
  • Use meaningful failure messages for important business validations.


54. Assertion Strategy in Selenium Framework

Test Case

    |

    v

Open Application

    |

    v

Perform Action

    |

    v

Wait for Required State

    |

    v

Capture Actual Result

    |

    v

Compare with Expected Result

    |

    v

TestNG Assertion

    |

    +-- PASS

    |

    +-- FAIL

    |

    v

Report


55. Assertions in a Real Login Framework

BaseTest

    |

    +-- Start WebDriver

    |

    v

LoginPage

    |

    +-- Enter Username

    +-- Enter Password

    +-- Click Login

    |

    v

HomePage

    |

    +-- Capture Dashboard State

    |

    v

TestNG Assertion

    |

    +-- Expected = Dashboard

    +-- Actual = Dashboard

    |

    v

PASS


56. Assertions and TestNG Reporting

Assertion results contribute to the overall TestNG test result. When an assertion fails, TestNG records the corresponding test method as failed unless the failure is handled through an expected exception or another framework-specific mechanism.

Assertion

    |

    +-- Pass

    |     |

    |     v

    |   Test Continues

    |

    +-- Fail

          |

          v

      Test Method Fails

          |

          v

        Report


57. Assertions with Data-Driven Testing

Assertions can be combined with DataProvider to validate multiple input combinations.

@DataProvider(name = "loginData")

public Object[][] loginData() {

    return new Object[][] {

        {"admin", "admin123", true},

        {"wrong", "wrong123", false},

        {"tester", "test123", true}

    };

}

 

@Test(dataProvider = "loginData")

public void verifyLogin(

        String username,

        String password,

        boolean expectedSuccess) {

 

    // Perform login

 

    boolean actualSuccess =

        driver.getCurrentUrl().contains("dashboard");

 

    Assert.assertEquals(

        actualSuccess,

        expectedSuccess

    );

}

This approach allows one test method to validate multiple test-data combinations.


58. Assertions with Negative Testing

Assertions are also important for negative testing. A negative test verifies that the application correctly rejects invalid input or prevents an invalid operation.

@Test

public void verifyInvalidLogin() {

    driver.findElement(By.id("username"))

          .sendKeys("wrongUser");

 

    driver.findElement(By.id("password"))

          .sendKeys("wrongPassword");

 

    driver.findElement(By.id("login"))

          .click();

 

    String errorMessage =

        driver.findElement(By.id("error"))

              .getText();

 

    Assert.assertEquals(

        errorMessage,

        "Invalid username or password"

    );

}


59. Assertions with Expected Exceptions

TestNG can also validate that a specific exception is expected from a test method.

@Test(expectedExceptions = ArithmeticException.class)

public void verifyExpectedException() {

    int result = 10 / 0;

}

In this case, the exception is part of the expected test behavior.


60. Assertion Methods Quick Reference

MethodExamplePurpose
assertEquals()Assert.assertEquals(actual, expected)Checks equality.
assertNotEquals()Assert.assertNotEquals(actual, unexpected)Checks inequality.
assertTrue()Assert.assertTrue(condition)Checks that condition is true.
assertFalse()Assert.assertFalse(condition)Checks that condition is false.
assertNull()Assert.assertNull(value)Checks that value is null.
assertNotNull()Assert.assertNotNull(value)Checks that value is not null.
assertSame()Assert.assertSame(first, second)Checks object identity.
assertNotSame()Assert.assertNotSame(first, second)Checks different object references.


61. Hard Assert vs SoftAssert Syntax

Hard Assertion

Assert.assertEquals(

    actual,

    expected

);

Soft Assertion

SoftAssert softAssert = new SoftAssert();

 

softAssert.assertEquals(

    actual,

    expected

);

 

softAssert.assertAll();


62. Practical E-Commerce Assertions

@Test

public void verifyProductAddedToCart() {

    productPage.searchProduct("Laptop");

 

    productPage.addProductToCart();

 

    String cartCount =

        cartPage.getCartItemCount();

 

    Assert.assertEquals(

        cartCount,

        "1",

        "Cart should contain one product"

    );

}

Checkout Validation

@Test

public void verifyCheckoutPage() {

    cartPage.clickCheckout();

 

    Assert.assertTrue(

        checkoutPage.isCheckoutPageDisplayed(),

        "Checkout page should be displayed"

    );

}


63. Practical Registration Assertions

@Test

public void verifyRegistrationSuccess() {

    registrationPage.enterName("John");

    registrationPage.enterEmail("[email protected]");

    registrationPage.enterPassword("Password123");

    registrationPage.clickRegister();

 

    String message =

        registrationPage.getSuccessMessage();

 

    Assert.assertEquals(

        message,

        "Registration successful"

    );

}


64. Practical Form Validation Assertions

@Test

public void verifyRequiredFieldValidation() {

    registrationPage.clickRegister();

 

    String error =

        registrationPage.getEmailErrorMessage();

 

    Assert.assertEquals(

        error,

        "Email is required"

    );

}


65. Practical Assertion Framework Structure

src/test/java

    |

    +-- tests

    |     |

    |     +-- LoginTest.java

    |     +-- RegistrationTest.java

    |     +-- SearchTest.java

    |     +-- CheckoutTest.java

    |

    +-- pages

    |     |

    |     +-- LoginPage.java

    |     +-- HomePage.java

    |     +-- CartPage.java

    |     +-- CheckoutPage.java

    |

    +-- base

    |     |

    |     +-- BaseTest.java

    |

    +-- utilities

          |

          +-- WaitUtils.java

          +-- ScreenshotUtils.java

Test classes perform business validations, page classes expose page functionality, and reusable utilities handle common framework operations.


66. Assertion Execution Flow in a Real Project

testng.xml

     |

     v

TestNG

     |

     v

@Test Method

     |

     v

Selenium Action

     |

     v

Synchronization

     |

     v

Actual Result

     |

     v

Expected Result

     |

     v

Assertion

     |

     +-- PASS

     |

     +-- FAIL

     |

     v

Test Report

     |

     +-- Logs

     +-- Screenshot

     +-- Failure Details


67. Common Interview Questions on Assertions

Q1. What is an assertion in TestNG?

An assertion is a validation mechanism used to compare actual application behavior with the expected result.

Q2. Why are assertions used in Selenium?

Selenium performs browser actions, while assertions verify whether the application produced the expected result.

Q3. What is the difference between assertEquals() and assertTrue()?

assertEquals() compares two values, while assertTrue() checks whether a Boolean condition is true.

Q4. What is assertFalse()?

assertFalse() verifies that a Boolean condition evaluates to false.

Q5. What is assertNotNull()?

It verifies that the supplied value or object is not null.

Q6. What is a hard assertion?

A hard assertion stops execution of the current test method when the assertion fails.

Q7. What is SoftAssert?

SoftAssert allows multiple assertions to be collected while allowing the test method to continue executing.

Q8. Why is assertAll() required with SoftAssert?

assertAll() evaluates the collected soft assertion failures and causes the test to fail when one or more validations failed.

Q9. Can multiple assertions be used in one test method?

Yes. Multiple assertions can be used when they validate related aspects of the same test scenario.

Q10. How do you validate a page title?

Assert.assertEquals(

    driver.getTitle(),

    "Expected Title"

);

Q11. How do you verify that an element is visible?

Assert.assertTrue(

    driver.findElement(By.id("login")).isDisplayed()

);

Q12. What is the difference between wait and assertion?

A wait synchronizes the test with the application state, while an assertion validates whether the resulting state is correct.

Q13. How can you add a failure message to an assertion?

Assert.assertTrue(

    condition,

    "Expected condition was not satisfied"

);

Q14. When should SoftAssert be used?

SoftAssert can be useful when multiple independent validations need to be collected before the final test result is evaluated.

Q15. Can assertions be used with DataProvider?

Yes. Assertions can validate the expected result for each data set supplied by a DataProvider.

Q16. Can assertions be used with Page Object Model?

Yes. Page Object Model can expose page actions and state information, while test methods perform business-level assertions.

Q17. What happens when a hard assertion fails?

The current test method stops at the failed assertion and TestNG records the test as failed.

Q18. What happens when a SoftAssert validation fails?

The test can continue executing subsequent statements, and the failure is reported when assertAll() is called.

Q19. Should every Selenium action have an assertion?

Not necessarily. Assertions should validate meaningful expected outcomes rather than being added mechanically after every Selenium action.

Q20. Why should assertions have meaningful messages?

Meaningful messages make failed automation tests easier to understand and debug.


68. Best Assertion Practices for Interviews and Projects

PracticeRecommendation
ValidationAlways validate important expected outcomes.
Assertion TypeChoose the assertion that best matches the expected condition.
Hard AssertionsUse for important checkpoints where continuing is not meaningful.
Soft AssertionsUse when multiple related validations should be collected.
assertAll()Always call it after relevant SoftAssert validations.
WaitsSynchronize before validating dynamic application states.
MessagesUse meaningful failure messages where helpful.
POMKeep page interactions organized separately from test scenarios.
DataProviderCombine assertions with multiple input data sets when appropriate.
MaintainabilityAvoid unnecessary or duplicate assertions.


69. Quick Revision

ConceptRemember
AssertionValidates actual result against expected behavior.
AssertTestNG class used for hard assertions.
assertEquals()Checks equality.
assertNotEquals()Checks inequality.
assertTrue()Checks that a condition is true.
assertFalse()Checks that a condition is false.
assertNull()Checks that a value is null.
assertNotNull()Checks that a value is not null.
assertSame()Checks object identity.
assertNotSame()Checks different object references.
SoftAssertAllows multiple validations to be collected.
assertAll()Evaluates collected SoftAssert failures.
WaitSynchronizes test execution with application state.
Assertion MessageExplains the reason for a validation failure.
DataProviderCan execute assertions against multiple data sets.
POMSeparates page actions from test validation logic.


70. Learning Roadmap

Core Java

    |

    v

Selenium WebDriver

    |

    v

Locators

    |

    v

WebElements

    |

    v

Browser Interactions

    |

    v

Waits & Synchronization

    |

    v

TestNG

    |

    +-- Test Methods

    +-- Test Annotations

    +-- Assertions

    +-- Test Groups

    +-- Test Dependencies

    +-- DataProvider

    +-- Test Execution

    |

    v

Page Object Model

    |

    v

Automation Framework

    |

    v

Maven

    |

    v

Git & GitHub

    |

    v

Reporting

    |

    v

Jenkins / CI/CD

    |

    v

Parallel Execution

    |

    v

Real-Time Selenium Project


71. Summary

Assertions are a fundamental part of TestNG-based Selenium automation. Selenium WebDriver performs browser interactions, while TestNG assertions validate whether the application behaves according to the expected requirements.

The most commonly used assertions include assertEquals(), assertNotEquals(), assertTrue(), assertFalse(), assertNull(), assertNotNull(), assertSame(), and assertNotSame(). TestNG also provides SoftAssert for scenarios where multiple validations need to be collected before the final result is evaluated.

Effective Selenium automation requires more than simply clicking buttons and entering data. A well-designed test should perform the required action, synchronize with the application when necessary, capture the actual result, compare it with the expected result, and use an appropriate assertion to determine the test outcome.

Assertions become even more useful when combined with Selenium WebDriver, Page Object Model, DataProvider, TestNG test methods, waits, reporting, screenshots, Maven, and CI/CD. This combination helps create structured, maintainable, and reliable automation test frameworks.


72. Course Resources

Learn more about Selenium WebDriver, TestNG, assertions, validations, automation frameworks, data-driven testing, and real-world Selenium projects through the following resources:

Selenium Training

Register for Course Demo

whatsapp